/* eslint no-underscore-dangle: 0 */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button, Table, Icon, Message, Grid, Dialog, Input, Checkbox, Select, Loading } from '@alifd/next';
import IceContainer from '@icedesign/container';
import axios from '../../../../instances/request';
import { withRouter } from 'react-router-dom';
import ReactDOM from "react-dom";
const TableExport = require('tableexport');
const moment = require('moment');

const { Row, Col } = Grid;

@withRouter
export default class InspectionWeekTable extends Component {
  static displayName = 'InspectionWeekTable';

  static propTypes = {
    limit: PropTypes.number,
    type: PropTypes.string,
    title: PropTypes.string,
    oid: PropTypes.string,
    sType: PropTypes.string,
    isBoweiSupport: PropTypes.bool,
  };

  static defaultProps = {
    limit: 8,
  };

  constructor(props) {
    super(props);
    this.state = {
      equipmentList: [],
      tableData: {
        totalCount: 0,
        pageSize: this.props.limit,
        currentPage: 1,
        list: [],
        __loading: false,
        scopes: [],
      },
      tableWidth: 800,
      value: {},
      loadingVisible: false,
    };

    this.counter = 0;
    this.exportTableCounter = 0;
    this.signWeekday = moment().weekday();
  }

  // todo: 这里不应该将数据请求与返回和组件绑定在一起的，这样做是错误的，应该是数据请求单独是一个函数，组件变换又是一个函数
  async fetchData ({ page }, callback) {
    const tableData = this.state.tableData;
    tableData.__loading = true;

    this.setState({ tableData });

    let res = await axios.post(
      '/inspectionRecord/week/content',
      {
        oid: this.props.oid
      }
    )
      .catch((err) => {
        Message.error(`巡视记录列表接口${err}`);
        return Promise.reject(err);
      });

    console.log("巡视记录列表接口", res);

    let { code, msg } = res.data;
    switch (code) {
      case 0:
        let {
          inspectionRecords,
          totalCount,
          count,
          d1Signatory,
          d2Signatory,
          d3Signatory,
          d4Signatory,
          d5Signatory,
          d6Signatory,
          d7Signatory,
          n1Signatory,
          n2Signatory,
          n3Signatory,
          n4Signatory,
          n5Signatory,
          n6Signatory,
          n7Signatory,
          superSignatory,
          abnormalRecord,
          scopes,
          createdAt,
        } = msg;
        scopes = scopes.map((scope, index) => {
          if ( index !== 0 ) {
            scope.rowIndex = scopes[index].scopeCount + scopes[index - 1].rowIndex;
          } else {
            scope.rowIndex = scope.scopeCount;
          }
          return scope;
        });
        console.log(scopes);
        // 重置counter
        this.counter = 0;
        this.exportTableCounter = 0;

        const tableData = this.state.tableData;
        tableData.list = inspectionRecords;
        tableData.totalCount = totalCount;
        tableData.scopes = scopes;
        tableData.__loading = false;

        this.d1Signatory = d1Signatory;
        this.d2Signatory = d2Signatory;
        this.d3Signatory = d3Signatory;
        this.d4Signatory = d4Signatory;
        this.d5Signatory = d5Signatory;
        this.d6Signatory = d6Signatory;
        this.d7Signatory = d7Signatory;

        this.n1Signatory = n1Signatory;
        this.n2Signatory = n2Signatory;
        this.n3Signatory = n3Signatory;
        this.n4Signatory = n4Signatory;
        this.n5Signatory = n5Signatory;
        this.n6Signatory = n6Signatory;
        this.n7Signatory = n7Signatory;

        this.superSignatory = superSignatory;
        this.abnormalRecord = abnormalRecord;

        Message.warning('处理时间可能较长，请耐心等待');
        this.setState({
          tableData,
        }, () => {
          this.setExportButton(callback);  // 刷新导出按钮
        });
        return createdAt;
        break;

      default:
        Message.error(`巡视记录列表接口code${code}`);
        return;
    }
  };

  /**
   * 得到设备列表
   * @param page
   * @param limit
   * @param createdAt
   * @return {Promise<{totalCount, equipmentList, count}>}
   */
  async getEquipmentList({ page = 1, limit = -1, beforeTime }) {
    const res = await axios
      .post('/equipment/list', {
        page: page,
        limit: limit,
        sType: this.props.type,
        beforeTime,
      });
    let { code, msg } = res.data;
    if( code !== 0 ) {
      throw new Error(`获取设备列表接口返回code为${code}`);
    }
    let { totalCount, equipmentList, count } = msg;
    return {
      totalCount,
      equipmentList,
      count,
    }
  }

  setExportButton(callback) {
    let recordTr = (
      <div>
        <td>监控异常情况记录：</td>
        <td>{this.abnormalRecord}</td>
      </div>
    );

    let signTr1 = (
      <div>
        <div>
          <td></td>
          <td></td>
          <td>周一</td>
          <td>周二</td>
          <td>周三</td>
          <td>周四</td>
          <td>周五</td>
          <td>周六</td>
          <td>周日</td>
        </div>
      </div>
    );

    let signTr2 = (
      <div>
        <td>IT白班人员签字：</td>
        <td></td>
        <td>{this.d1Signatory}</td>
        <td>{this.d2Signatory}</td>
        <td>{this.d3Signatory}</td>
        <td>{this.d4Signatory}</td>
        <td>{this.d5Signatory}</td>
        <td>{this.d6Signatory}</td>
        <td>{this.d7Signatory}</td>
      </div>
    );

    let signTr3 = (
      <div>
        <td>IT夜班人员签字：</td>
        <td></td>
        <td>{this.n1Signatory}</td>
        <td>{this.n2Signatory}</td>
        <td>{this.n3Signatory}</td>
        <td>{this.n4Signatory}</td>
        <td>{this.n5Signatory}</td>
        <td>{this.n6Signatory}</td>
        <td>{this.n7Signatory}</td>
      </div>
    );

    let signTr4 = (
      <div id='signTr4'>
        <td>博维Support人员签字：</td>
        <td></td>
        <td>{this.superSignatory}</td>
      </div>
    );

    let child;
    if(document.getElementById('abnormalRecord')) {
      child = document.getElementById('abnormalRecord');
      child.parentNode.removeChild(child);
    }
    if(document.getElementById('signTr1')) {
      child = document.getElementById('signTr1');
      child.parentNode.removeChild(child);
    }
    if(document.getElementById('signTr2')) {
      child = document.getElementById('signTr2');
      child.parentNode.removeChild(child);
    }
    if(document.getElementById('signTr3')) {
      child = document.getElementById('signTr3');
      child.parentNode.removeChild(child);
    }
    if(document.getElementById('signTr4')) {
      child = document.getElementById('signTr4');
      child.parentNode.removeChild(child);
    }

    let tr_record = document.createElement('tr');
    tr_record.id = 'abnormalRecord';
    let tr_sign1 = document.createElement('tr');
    tr_sign1.id = 'signTr1';
    let tr_sign2 = document.createElement('tr');
    tr_sign2.id = 'signTr2';
    let tr_sign3 = document.createElement('tr');
    tr_sign3.id = 'signTr3';
    let tr_sign4 = document.createElement('tr');
    tr_sign4.id = 'signTr4';
    let tbody = document.querySelector('#exportTable tbody');
    tbody.appendChild(tr_record);
    tbody.appendChild(tr_sign1);
    tbody.appendChild(tr_sign2);
    tbody.appendChild(tr_sign3);
    tbody.appendChild(tr_sign4);

    ReactDOM.render(recordTr, tr_record, () => {
      ReactDOM.render(signTr1, tr_sign1, () => {
        ReactDOM.render(signTr2, tr_sign2, () => {
          ReactDOM.render(signTr3, tr_sign3, () => {
            ReactDOM.render(signTr4, tr_sign4, () => {
              let tableId = 'exportTable';
              TableExport(document.getElementById(tableId), {
                formats: ['xlsx'],
                trimWhitespace: false,
                exportButtons: true,
                filename: `${this.props.title}-${this.props.createdTime}`,
              });
              callback && callback();
            });
          });
        });
      });
    });
  }

  async componentDidMount() {
    let createdAt = await this.fetchData({ page: 1});
    let { equipmentList } = await this.getEquipmentList({ limit: -1 , beforeTime: createdAt });
    this.setState({
      equipmentList,
      tableWidth: document.body.clientWidth - 290 + 60,
    }, () => {
      this.setExportButton();
    });
  }

  onCheckboxChange(id, weekday) {
    this.setState({
      loadingVisible: true
    }, () => {
      let checkbox = document.getElementById(`checkbox_${id}`).parentNode.parentNode;   // 用户的点击操作会对此元素造成影响！这里就已经能够获取到更新！
      let newState = checkbox.classList.contains('checked') ? 0 : 1;
      if(newState === 0) {
        checkbox.classList.add('checked');
        checkbox.style.backgroundColor = 'white';
        checkbox.style.color = 'black';
      } else {
        checkbox.classList.remove('checked');
        checkbox.style.backgroundColor = 'red';
        checkbox.style.color = 'white';
      }

      axios.post('/inspectionRecord/update' ,{
        id,
        equipmentState: newState,
        weekday,
      }).then((res)=> {
        this.setState({
          loadingVisible: false,
        });
        let { code, msg } = res.data;
        code === 0 ? Message.success('修改成功') : Message.error('修改失败，请刷新页面重试');
        // this.fetchData({page: 1});
      });
    });

  }

  /**
   * 渲染每一行的数据
   */
  renderInspectionData(weekday, value, i, row) {
    let equipmentState = row.equipmentState;
    let checkbox = '';
    equipmentState.forEach((ele, idx) => {
      if(ele.weekday === weekday) {
        checkbox = (
          <Checkbox
            id={`checkbox_${ele.id}`}
            onChange={this.onCheckboxChange.bind(this, ele.id, weekday)}
            style={ele.state === 1 ? { backgroundColor: 'red', color: 'white', cursor: 'pointer' } : { cursor: 'pointer' }}
            label={ele.label}
            defaultChecked={ele.state === 0}
          />
        );
      }
    });
    return checkbox;
  }

  renderExportInspectionData(weekday, value, i, row) {
    let equipmentState = row.equipmentState;
    let div = '';
    equipmentState.forEach((ele, idx) => {
      if(ele.weekday === weekday) {
        div = (
          <div>{ele.label}<u>{ele.state === 0 ? `√` : '☓'}</u></div>   // mac真棒 option + V 打出这个：√
        )
      }
    });
    return div;
  }

  confirmRecord(type) {
    let dialog = Dialog.show({
      isFullScreen: true,
      title: '请输入您的签名',
      content: (
        <div>
          <div style={{
            ...styles.formItem,
          }}>
            <div style={styles.formLabel}>签名</div>
            <Input
              style={{width: '150px'}}
              placeholder='签名'
              onChange={function(value) {
                this.sign = value;
              }.bind(this)}
            />
          </div>
          {
            this.props.isBoweiSupport ||
            <div style={{
              ...styles.formItem,
              marginBottom: '20px',
            }}>
              <div style={styles.formLabel}>所属日期</div>
              <Select
                style={{width: '150px'}}
                defaultValue={moment().weekday()}
                onChange={function(v) {
                  this.signWeekday = v;
                }.bind(this)}
                dataSource={[{
                  label: '周一',
                  value: 1
                },{
                  label: '周二',
                  value: 2
                },{
                  label: '周三',
                  value: 3
                },{
                  label: '周四',
                  value: 4
                },{
                  label: '周五',
                  value: 5
                },{
                  label: '周六',
                  value: 6
                },{
                  label: '周日',
                  value: 7
                }]}
              />
            </div>
          }
        </div>
      ),
      onOk: () => {
        return axios.post('/inspectionRecord/confirm', {
          oid: this.props.oid,
          sign: this.sign,
          signWeekday: this.signWeekday,
          type,
        }).then((res) => {
          let {code} = res.data;
          Message.success('签名成功');
          return this
            .fetchData({page : 1})
            .then(() => {
              dialog.hide();
            });
        });
      },
      onCancel: () => {
        dialog.hide();
      }
    });
  }

  addAbnormalRecord(e) {
    e.preventDefault();

    let dialog = Dialog.show({
      isFullScreen: true,
      title: '填写当天异常记录',
      content: (
        <div style={{ padding: '10px 15px'}}>
          <Input.TextArea
            style={{width: '300px'}}
            placeholder='如果已有异常记录，重复提交会覆盖原有记录'
            onChange={function(value) {
              this.abnormalRecord = value;
            }.bind(this)}
          />
        </div>
      ),
      onOk: () => {
        return axios.post('/inspectionRecord/abnormal/add', {
          oid: this.props.oid,
          abnormalRecord: this.abnormalRecord,
        }).then((res) => {
          let {code} = res.data;
          Message.success('提交异常记录成功');
          return this
            .fetchData({page : 1})
            .then(() => {
              dialog.hide();
            });
        });
      },
      onCancel: () => {
        dialog.hide();
      }
    })
  }

  // 会遍历行五次，而且这五次返回的数据要一致才能正确显示
  setCellProps(rowIndex, colIndex, dataIndex, record) {
    let scopes = this.state.tableData.scopes;
    if( colIndex === 0 && scopes.length !== 0 ) {  // 如果是设备主类别
      let scopeIndex = this.counter;

      if(rowIndex === (scopes[scopeIndex].rowIndex)) {  // 如果到了要换行的程度，则换行，scopeIndex+1
        this.counter += 1;
        scopeIndex = this.counter;
      }
      if(scopeIndex === (scopes.length - 1)) {  // 如果到了scopes的最后一个元素，将counter置为0
        this.counter = 0;
      }

      return {
        colSpan: 1,
        rowSpan: scopes[scopeIndex].scopeCount
      };
    }
  }

  setExportCellProps(rowIndex, colIndex, dataIndex, record) {
    let scopes = this.state.tableData.scopes;
    if( colIndex === 0 && scopes.length !== 0 ) {  // 如果是设备主类别
      let scopeIndex = this.exportTableCounter;

      if(rowIndex === (scopes[scopeIndex].rowIndex)) {  // 如果到了要换行的程度，则换行，scopeIndex+1
        this.exportTableCounter += 1;
        scopeIndex = this.exportTableCounter;
      }
      if(scopeIndex === (scopes.length - 1)) {  // 如果到了scopes的最后一个元素，将counter置为0
        this.exportTableCounter = 0;
      }

      return {
        colSpan: 1,
        rowSpan: scopes[scopeIndex].scopeCount
      };
    }
  }

  /**
   * 导出
   */
  handleExport() {
    this.fetchData({ page : 1 }, () => {      // 更新按钮后再进行点击
      document.getElementsByClassName('button-default xlsx')[0].click();
    });
  }

  render() {
    const tableData = this.state.tableData;

    return (
      <div className="operation-table">
        <Loading visible={this.state.loadingVisible}
                 fullScreen
                 shape="fusion-reactor"
        />
        <IceContainer style={styles.cardContainer}>
          <Table
            id="exportTable"
            getCellProps={this.setExportCellProps.bind(this)}
            dataSource={tableData.list}
            className="basic-table"
            hasBorder={true}
            primaryKey="key"
            style={{ textAlign: 'center', visibility:'hidden', height: '1px', width: this.state.tableWidth }}
          >
            <Table.Column
              title='设备类别'
              width={100}
              align='center'
              key='key'
              dataIndex='scope'
              lock='left'
            />
            <Table.Column
              title='设备名'
              width={100}
              align='center'
              key='key'
              dataIndex='equipmentName'
              lock='left'
            />
            <Table.Column
              title='周一'
              width={100}
              align='center'
              key='key'
              cell={this.renderExportInspectionData.bind(this, 1)}
            />
            <Table.Column
              title='周二'
              width={100}
              align='center'
              key='key'
              cell={this.renderExportInspectionData.bind(this, 2)}
            />
            <Table.Column
              title='周三'
              width={100}
              align='center'
              key='key'
              cell={this.renderExportInspectionData.bind(this, 3)}
            />
            <Table.Column
              title='周四'
              width={100}
              align='center'
              key='key'
              cell={this.renderExportInspectionData.bind(this, 4)}
            />
            <Table.Column
              title='周五'
              width={100}
              align='center'
              key='key'
              cell={this.renderExportInspectionData.bind(this, 5)}
            />
            <Table.Column
              title='周六'
              width={100}
              align='center'
              key='key'
              cell={this.renderExportInspectionData.bind(this, 6)}
            />
            <Table.Column
              title='周日'
              width={100}
              align='center'
              key='key'
              cell={this.renderExportInspectionData.bind(this, 7)}
            />
          </Table>
          <Row>
            <Col>
              <div style={styles.back} onClick={this.props.history.goBack}>
                <Icon type="arrow-left" />返回列表
              </div>
            </Col>
            <Col>
              <div className="operation-table-title" style={styles.operationTableTitle}>
                { this.props.title }
              </div>
            </Col>
            <Col>
              {
                this.props.isBoweiSupport && <Button
                  style={styles.addButton}
                  type='secondary'
                  onClick={this.confirmRecord.bind(this)}
                  size='small'
                >
                  博维人员签字
                </Button>
              }
              {
                this.props.isBoweiSupport || <Button
                  style={styles.addButton}
                  type='secondary'
                  onClick={this.confirmRecord.bind(this, 'night')}
                  size='small'
                >
                  夜班签字
                </Button>
              }
              {
                this.props.isBoweiSupport || <Button
                  style={styles.addButton}
                  type='secondary'
                  onClick={this.confirmRecord.bind(this, 'day')}
                  size='small'
                >
                  白班签字
                </Button>
              }
              <Button
                style={{
                  ...styles.addButton,
                  background: '#A2221C',
                  border: '1px solid #A2221C',
                  color: '#f2f2f2',
                }}
                type='default'
                shape="warning"
                size='small'
                onClick={this.addAbnormalRecord.bind(this)}
              >
                填写异常记录
              </Button>
              <Button
                style={{
                  ...styles.addButton,
                }}
                className='exportButton'
                type='primary'
                size='small'
                onClick={this.handleExport.bind(this)}
              >
                导出到Excel
              </Button>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <div style={{ width: this.state.tableWidth }}>
                <Table
                  isZebra={true}
                  // todo: 左侧aside全屏，右侧content变成scroll以后，表头不再sticky了，很玄学，所以改成固定高度表
                  fixedHeader={true}
                  maxBodyHeight={350}
                  getCellProps={this.setCellProps.bind(this)}
                  // stickyHeader={true}
                  dataSource={tableData.list}
                  className="basic-table"
                  loading={tableData.__loading}
                  hasBorder={true}
                  primaryKey="key"
                  style={{ textAlign: 'center' }}
                >
                  <Table.Column
                    title='设备类别'
                    width={100}
                    align='center'
                    key='key'
                    dataIndex='scope'
                    lock='left'
                  />
                  <Table.Column
                    title='设备名'
                    width={100}
                    align='center'
                    key='key'
                    dataIndex='equipmentName'
                    lock='left'
                  />
                  <Table.Column
                    title='周一'
                    width={100}
                    align='center'
                    key='key'
                    cell={this.renderInspectionData.bind(this, 1)}
                  />
                  <Table.Column
                    title='周二'
                    width={100}
                    align='center'
                    key='key'
                    cell={this.renderInspectionData.bind(this, 2)}
                  />
                  <Table.Column
                    title='周三'
                    width={100}
                    align='center'
                    key='key'
                    cell={this.renderInspectionData.bind(this, 3)}
                  />
                  <Table.Column
                    title='周四'
                    width={100}
                    align='center'
                    key='key'
                    cell={this.renderInspectionData.bind(this, 4)}
                  />
                  <Table.Column
                    title='周五'
                    width={100}
                    align='center'
                    key='key'
                    cell={this.renderInspectionData.bind(this, 5)}
                  />
                  <Table.Column
                    title='周六'
                    width={100}
                    align='center'
                    key='key'
                    cell={this.renderInspectionData.bind(this, 6)}
                  />
                  <Table.Column
                    title='周日'
                    width={100}
                    align='center'
                    key='key'
                    cell={this.renderInspectionData.bind(this, 7)}
                  />
                </Table>
              </div>
            </Col>
          </Row>
          <Row style={styles.tableRow}>
            <Col>
              <div style={{
                marginLeft: '20px',
              }}><p>监控异常情况记录：</p><p>{this.abnormalRecord}</p></div>
            </Col>
          </Row>
          <Row style={styles.tableRow}>
            <Col>
              <span style={{
                marginLeft: '20px',
              }}>IT白班人员签字：</span>
              <span style={{
                marginLeft: '20px',
              }}>
                周一-{this.d1Signatory}
              </span>
              <span style={{
                marginLeft: '20px',
              }}>
                周二-{this.d2Signatory}
              </span>
              <span style={{
                marginLeft: '20px',
              }}>
                周三-{this.d3Signatory}
              </span>
              <span style={{
                marginLeft: '20px',
              }}>
                周四-{this.d4Signatory}
              </span>
              <span style={{
                marginLeft: '20px',
              }}>
                周五-{this.d5Signatory}
              </span>
              <span style={{
                marginLeft: '20px',
              }}>
                周六-{this.d6Signatory}
              </span>
              <span style={{
                marginLeft: '20px',
              }}>
                周日-{this.d7Signatory}
              </span>
            </Col>
          </Row>
          <Row style={styles.tableRow}>
            <Col>
              <span style={{
                marginLeft: '20px',
              }}>IT夜班人员签字：</span>
              <span style={{
                marginLeft: '20px',
              }}>
                周一-{this.n1Signatory}
              </span>
              <span style={{
                marginLeft: '20px',
              }}>
                周二-{this.n2Signatory}
              </span>
              <span style={{
                marginLeft: '20px',
              }}>
                周三-{this.n3Signatory}
              </span>
              <span style={{
                marginLeft: '20px',
              }}>
                周四-{this.n4Signatory}
              </span>
              <span style={{
                marginLeft: '20px',
              }}>
                周五-{this.n5Signatory}
              </span>
              <span style={{
                marginLeft: '20px',
              }}>
                周六-{this.n6Signatory}
              </span>
              <span style={{
                marginLeft: '20px',
              }}>
                周日-{this.n7Signatory}
              </span>
            </Col>
          </Row>
          <Row style={styles.tableRow}>
            <Col>
              <span style={{
                marginLeft: '20px',
              }}>博维Support人员签字：</span>
              <span>
                  {this.superSignatory}
              </span>
            </Col>
          </Row>
        </IceContainer>
      </div>
    );
  }
}

const styles = {
  back: {
    margin: '10px 0 30px 10px',
    fontSize: '18px',
    fontWeight: '500',
    color: '#5584FF',
    cursor: 'pointer',
  },
  cardContainer: {
    padding: '10px 10px 20px 10px',
  },
  titleCol: {
    display: 'flex',
    flexDirection: 'row',
  },
  operBtn: {
    display: 'inline-block',
    width: '24px',
    height: '24px',
    borderRadius: '999px',
    color: '#929292',
    background: '#f2f2f2',
    textAlign: 'center',
    cursor: 'pointer',
    lineHeight: '24px',
    marginRight: '6px',
  },
  paginationContainer: {
    textAlign: 'right',
    paddingTop: '26px',
  },
  operationTableTitle: {
    fontSize: '18px',
    fontWeight: 'bold',
    fontColor: 'black',
    height: '45px',
    lineHeight: '45px',
    textAlign: 'center',
  },
  addButton: {
    float: 'right',
    margin: '14px 15px 0 0',
  },
  formItem: {
    display: 'flex',
    alignItems: 'center',
    margin: '10px 40px'
  },
  formLabel: {
    minWidth: '80px',
  },
  tableRow: {
    background: '#FFFFFF',
    color: '#333333',
    fontSize: '14px',
    border: '1px solid #DCDEE3',
    borderTop: 'none',
    padding: '10px 10px',
  },

};
